
//群组详情

package com.ja.openchat.ui.chat.group;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.BuildConfig;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityGroupChatSettingsNewBinding;
import com.ja.openchat.databinding.ActivityGroupChatSettingsSingleBinding;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.chat.group.adapter.MemberGridAdapter;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.search.ChatHistorySearchActivity;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.ja.openchat.ui.message.adapter.SimpleFragmentPagerAdapter;
import com.ja.openchat.viewmodels.GroupChatSettingNewViewModel;
import com.ja.openchat.viewmodels.GroupChatSettingSingleViewModel;
import com.ja.openchat.viewmodels.GroupSettingViewModel;
import com.ja.openchat.views.ChatGroupNickNameDialog;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.ChatUserVideoMenuDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupAnimation;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.group.GroupMemberInfo;
import com.zy.openchat.core.model.group.SuperGroupFullInfo;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.MediaUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import me.goldze.mvvmhabit.base.BaseActivity;

import static com.ja.openchat.ui.chat.group.MoreMemberActivity.BUNDLE_SUPERGROUP_FULLINFO;
import static com.ja.openchat.ui.chat.group.MoreMemberActivity.BUNDLE_SUPER_GROUPINFO;

public class GroupChatSettingsSingleActivity extends BaseActivity<ActivityGroupChatSettingsSingleBinding, GroupChatSettingSingleViewModel> implements View.OnClickListener {

    public static final int Group_Chat_Settings_Request = 100;
    public static final int Group_Chat_Settings_Result_To_Quit_Group = 101;

    public static void start(Activity activity, ChatInfo chat) {
        Intent intent = new Intent();
        intent.setClass(activity, GroupChatSettingsSingleActivity.class);
        intent.putExtra("chat", chat);
        activity.startActivityForResult(intent, Group_Chat_Settings_Request);
    }

    public ChatInfo chatInfo, chatInfo2;
    public SuperGroupInfo super_groupInfo;
    public SuperGroupFullInfo super_groupFullInfo;
    private List<GroupMemberInfo> orgi_membersList = new ArrayList<>();
    private List<GroupMemberInfo> orgi_memberIsManagersList = new ArrayList<>();
    private GroupSettingViewModel groupSettingViewModel;

    private MemberGridAdapter memberIsManagerGridAdapter;
    private List<GroupMemberInfo> membersList = new ArrayList<>();


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_chat_settings_single;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public GroupChatSettingSingleViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(GroupChatSettingSingleViewModel.class);
    }


    @Override
    public void initView() {
        super.initView();
        binding.toolbar.tvBarTitle.setText(getString(R.string.group_details));
        binding.toolbar.tvBarTitle.setText("");
        if (getIntent() != null) {
            chatInfo = getIntent().getParcelableExtra("chat");
        } else {
            chatInfo = new ChatInfo();
        }
        chatInfo2 = chatInfo;
        binding.headerImageView.setTextSize(20);
        viewModel.setContext(this, binding);
        groupSettingViewModel = ViewModelProviders.of(this).get(GroupSettingViewModel.class);
        binding.toolbar.tvOkRight.setBackground(ContextCompat.getDrawable(this, R.drawable.transparent_shape));
        binding.toolbar.tvOkRight.setTextColor(ContextCompat.getColor(this, R.color.nav_btn_bg));
        binding.toolbar.tvOkRight.setText(getString(R.string.edit_text));
        binding.toolbar.tvOkRight.setVisibility(View.INVISIBLE);
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //刷新UI
        syncChatInfo();
        //检查状态
        checkUserChatState();
        syncFullGroupInfo();

        resetGroupNickName();
        List<Fragment> fragments = new ArrayList<>();
        SimpleFragmentPagerAdapter fragmentAdater = null;

        if(BuildConfig.ShowLocal_ChatRecord){
            fragments.add(GroupSettingChildFragment.newInstance(0, chatInfo));
            fragments.add(GroupSettingChildFragment.newInstance(1, chatInfo));
            fragments.add(GroupSettingChildFragment.newInstance(2, chatInfo));
            fragments.add(GroupSettingChildFragment.newInstance(3, chatInfo));
            fragments.add(GroupSettingChildFragment.newInstance(4, chatInfo));
            fragments.add(GroupSettingChildFragment.newInstance(5, chatInfo));
            fragmentAdater = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), fragments
                    , new String[]{getString(R.string.member_text), getString(R.string.media_text), getString(R.string.file_text), getString(R.string.voice_text), getString(R.string.link_text), "GIF"});
        }else{
            fragments.add(GroupSettingChildFragment.newInstance(0, chatInfo2));

            fragmentAdater = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), fragments
                    , new String[]{getString(R.string.member_text)});
        }
        binding.viewPager.setAdapter(fragmentAdater);
        binding.viewPager.setOffscreenPageLimit(fragments.size());
        binding.tablayout.setupWithViewPager(binding.viewPager);

        binding.llGroupNotice.setOnClickListener(this);
        binding.llGroupMedia.setOnClickListener(this);
        binding.llSearch.setOnClickListener(this);
        binding.shareLinkLayout1.setOnClickListener(this);
        binding.groupNikyView1.setOnClickListener(this);
        binding.groupSummaryLayout1.setOnClickListener(this);
        binding.llChatHistory.setOnClickListener(this);
        binding.llTousu.setOnClickListener(this);
        binding.llGroupLogout.setOnClickListener(this);
        binding.sbDarao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                muteSwitchClick();
            }
        });



        binding.headerImageView.setOnClickListener(this);
        binding.addMemberBtn.setOnClickListener(this);
        binding.closeNotifyBtn.setOnClickListener(this);
        binding.searchMemberBtn.setOnClickListener(this);
        binding.moreHandleBtn.setOnClickListener(this);
        binding.shareLinkLayout.setOnClickListener(this);
        binding.qrImg.setOnClickListener(this);
        binding.groupAnnLayout.setOnClickListener(this);
        binding.groupSummaryLayout.setOnClickListener(this);
        binding.toolbar.tvOkRight.setOnClickListener(this);
        binding.groupNikyView.setOnClickListener(this);

        binding.groupMember.setOnClickListener(this);
        memberListUI();
    }

    public void resetUI() {
        binding.groupName.setText(chatInfo.title);
        binding.headerImageView.showGroup(chatInfo, XPopupUtils.dp2px(this, (int) getResources().getDimension(R.dimen.x70)));
        binding.closeNotifyBtn.setActivated(chatInfo.default_disable_notification);
        binding.closeNotifyBtn.setText(chatInfo.default_disable_notification ? getString(R.string.open_notifiy) : getString(R.string.off_annocement));

        binding.sbDarao.setChecked(chatInfo.default_disable_notification);

        boolean canEditGroupSettings = canEditGroupSetting();

        int onlineNumber = 0;
        if (orgi_membersList != null && orgi_membersList.size() > 0) {
            for (GroupMemberInfo iteminfo : orgi_membersList) {
                UserInfo userInfo = UserInfo.getUserInfo(iteminfo.user_id);
                if (userInfo != null && userInfo.isOnline()) {
                    onlineNumber++;
                }
            }
        }
        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
        if(configInfo==null||configInfo.shown_online_members){
            binding.groupMemberStatusStr.setVisibility(View.VISIBLE);
            binding.groupMemberStatusStr.setText(String.format(getString(R.string.total_online_desc_text), groupMemberInfos.size(), onlineNumber));
        }else{
            binding.groupMemberStatusStr.setVisibility(View.GONE);
        }

        if (super_groupFullInfo == null || TextUtils.isEmpty(super_groupFullInfo.invite_link)) {
            binding.qrImg.setVisibility(View.GONE);
            binding.shareUrl.setText(getString(R.string.group_link_not_set));
            binding.shareUrl1.setText(getString(R.string.group_link_not_set));
        } else {
            binding.qrImg.setVisibility(View.VISIBLE);
            binding.shareUrl.setText(super_groupFullInfo.invite_link);
            binding.shareUrl1.setText(super_groupFullInfo.invite_link);
        }
//        if (super_groupFullInfo == null || TextUtils.isEmpty(super_groupFullInfo.group_description)) {
//            binding.summaryContent.setText(getString(R.string.group_introduction_not_set));
//        } else {
//            binding.summaryContent.setText(super_groupFullInfo.group_description);
//        }
        if (canEditGroupSetting()) {
//            binding.summaryArrow.setVisibility(View.VISIBLE);
//            binding.annContentArrow.setVisibility(View.VISIBLE);
//            binding.toolbar.tvOkRight.setVisibility(View.VISIBLE);
        } else {
//            binding.summaryArrow.setVisibility(View.GONE);
//            binding.annContentArrow.setVisibility(View.GONE);
//            binding.toolbar.tvOkRight.setVisibility(View.GONE);
        }
        if(TextUtils.isEmpty(groupUserNickName)){
            binding.nickNameText.setText(UserInfo.getUserInfo().displayName());
        }else{
            binding.nickNameText.setText(groupUserNickName);
        }

        if(canEditGroupSettings){
            binding.llGroupName.setOnClickListener(this);
            binding.ivGroupNameArrow.setVisibility(View.VISIBLE);
        }else {
            binding.llGroupName.setOnClickListener(null);
            binding.ivGroupNameArrow.setVisibility(View.GONE);
        }

        if(canEditGroupSettings){
            binding.llGroupSettings.setOnClickListener(this);
            binding.llGroupSettings.setVisibility(View.VISIBLE);
        }else {
            binding.llGroupSettings.setOnClickListener(null);
            binding.llGroupSettings.setVisibility(View.GONE);
        }
    }

    public void setGroupUserNickName(String nickName){
        groupUserNickName = nickName;
        resetUI();
    }

    private boolean canInvideMember() {
        boolean canInvide = canEditGroupSetting();
        if (canInvide) {
            return canInvide;
        }
        return chatInfo.permissions != null && chatInfo.permissions.can_invite_users;
    }

    public void onClick(@NotNull View view) {
        switch (view.getId()) {
            case R.id.headerImageView:
                //此处无需点击
                if (canEditGroupSetting()) {
                    //设置群组头像
                    MediaUtils.choosePhoto(this, true);
                }
                break;

            case R.id.add_member_btn: {
                if (canInvideMember()) {
                    ContactChooseActivity.startWithInviteMember(this, chatInfo.id, orgi_membersList);
                } else {
                    showErrorTip(getString(R.string.no_permission_invite_new_member));
                }
            }
            break;
            case R.id.close_notify_btn:
                muteSwitchClick();
                break;

            case R.id.more_handle_btn:
                String[] titles;
                if (isOwnerGroup()) {
                    titles = new String[]{getString(R.string.complaint_text), getString(R.string.find_chat_content), getString(R.string.disband_the_group)};
                } else {
                    titles = new String[]{getString(R.string.complaint_text), getString(R.string.find_chat_content), getString(R.string.exit_group_chat)};
                }
                new XPopup.Builder(this)
                        .atView(view)
                        .offsetY(0)
                        .hasShadowBg(false)
                        .popupAnimation(PopupAnimation.NoAnimation)
                        .asAttachList(titles, null, new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                if (position == 0) {
                                    PreviewWebViewActivity.loadUrl(GroupChatSettingsSingleActivity.this, getString(R.string.complaint_text), Constants.KHostEReport);
                                } else if (position == 1) {
                                    ChatHistorySearchActivity.start(GroupChatSettingsSingleActivity.this, chatInfo,-1);
                                } else {
                                    if (isOwnerGroup()) {
                                        deleteGroupConfirm();
                                    } else {
                                        delAndLeftConfirm();
                                    }
                                }
                            }
                        }).show();
                break;

            case R.id.qr_img:
                viewModel.goQrcodeActivity(chatInfo, super_groupFullInfo);
                break;

            case R.id.tv_ok_right:
                EditGroupChatActivity.start(GroupChatSettingsSingleActivity.this, annContentStr, chatInfo);
                break;

            //ssssssssssssssssssssss

            case R.id.group_ann_layout:
            case R.id.ll_group_notice:
                //群公告
                ModifyFieldActivity.start_setGroupNotice(this, chatInfo.id, annContentStr, canEditGroupSetting());
                break;

            case R.id.ll_group_media:
                //图片 文件 语音
                GroupChatMediaActivity.start(this,chatInfo);
                break;
            case R.id.search_member_btn:
            case R.id.group_member:
                Bundle bundle = new Bundle();
                bundle.putParcelable("chat", chatInfo);
                bundle.putParcelable("chat2", chatInfo2);
                bundle.putParcelable(BUNDLE_SUPER_GROUPINFO, super_groupInfo);
                bundle.putParcelable(BUNDLE_SUPERGROUP_FULLINFO, super_groupFullInfo);
                startContainerActivity(MoreMemberActivity.class.getCanonicalName(), bundle);
                break;

            case R.id.share_title_1:
            case R.id.share_title:
                if (super_groupFullInfo != null && !TextUtils.isEmpty(super_groupFullInfo.invite_link)) {
                    ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    if (clipboardManager != null) {
                        ClipData clipData = ClipData.newPlainText("copyContent", super_groupFullInfo.invite_link);
                        clipboardManager.setPrimaryClip(clipData);
                        ToastUtils.showShort(getString(R.string.copied_text));
                    }
                } else {
                    showErrorTip(getString(R.string.group_link_not_set_to_reset));
                }
                break;
            case R.id.share_link_layout_1:
            case R.id.share_link_layout:
                //分享链接
                GroupInviteLinkActivity.start(this, chatInfo, super_groupFullInfo, canEditGroupSetting());
                break;

            case R.id.group_niky_view_1:
            case R.id.group_niky_view:
                //本群昵称
                ModifyFieldActivity.start_setGroupNickName(this, chatInfo.id, groupUserNickName==null?UserInfo.getUserInfo().displayName():groupUserNickName);
                break;
            case R.id.group_summary_layout_1:
            case R.id.group_summary_layout:
                //设置群简介
                String des = "";
                if (super_groupFullInfo != null && !TextUtils.isEmpty(super_groupFullInfo.group_description)) {
                    des = super_groupFullInfo.group_description;
                }
                ModifyFieldActivity.start_setGroupSummary(this, chatInfo.id,des, canEditGroupSetting());
                break;
            case R.id.ll_chat_history:
            case R.id.ll_search:
                //查找聊天内容
                ChatHistorySearchActivity.start(GroupChatSettingsSingleActivity.this, chatInfo,-1);
                break;
            case R.id.ll_tousu:
                //投诉
                PreviewWebViewActivity.loadUrl(GroupChatSettingsSingleActivity.this, getString(R.string.complaint_text), Constants.KHostEReport);
                break;
            case R.id.ll_group_logout:
                //退出群聊
                if (isOwnerGroup()) {
                    deleteGroupConfirm();
                } else {
                    delAndLeftConfirm();
                }
                break;
            case R.id.ll_group_name:
                //修改群名称
//                ModifyFieldActivity.start_setGroupName(this, chatInfo.id, binding.groupName.getText().toString());
                new XPopup.Builder(this)
                        .hasShadowBg(true)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .moveUpToKeyboard(true)
                        .borderRadius(10)
                        .atView(binding.llGroupName)
                        .asCustom(new ChatGroupNickNameDialog(this, chatInfo.id,binding.groupName.getText().toString(), new ChatGroupNickNameDialog.OnItemClickListner() {

                            @Override
                            public void clickPostion(int position, ChatInfo postion) {

                            }
                        })).show();
                break;
            case R.id.ll_group_settings:
                //群组权限设置
//                GroupChatManagerActivity.start(this, chatInfo);
                EditGroupManagerActivity.start(GroupChatSettingsSingleActivity.this, annContentStr, chatInfo);
                break;

        }
    }

    private void deleteGroupConfirm() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(getString(R.string.question_disband_group));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteGroup();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void deleteGroup() {
        showProgress();
        TelegramManager.getTelegramManager().deleteGroup(this, chatInfo.superGroupId(), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                } else {
//                    setResult(Group_Chat_Settings_Result_To_Quit_Group);
//                    finish();
                    startActivity(new Intent(GroupChatSettingsSingleActivity.this, MainActivity.class));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void muteSwitchClick() {
        showProgress();
        TelegramManager.getTelegramManager().toggleChatDisableNotification(this, chatInfo.id, !chatInfo.default_disable_notification, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                    resetUI();
                } else {
                    syncChatInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
                resetUI();
            }
        });
    }

    private void delAndLeftConfirm() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(getString(R.string.leave_group_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delAndLeft();
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void delAndLeft() {
        showProgress();
        TelegramManager.getTelegramManager().leaveGroup(this, chatInfo.id, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip("退出群组失败，请稍后重试, " + obj.errString);
                } else {
                    startActivity(new Intent(GroupChatSettingsSingleActivity.this, MainActivity.class));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void syncChatInfo() {
        if (chatInfo != null) {
            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(chatInfo.id);
            if (chat != null) {
                chatInfo = chat;
            }
        }
        resetUI();
    }

    public void clickMember(GroupMemberInfo member, boolean isManager) {
        if (member.isOptAdd()) {
            if (isManager) {//增加管理员
                ContactChooseActivity.startWithAddManager(this, chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            } else {//增加成员
                ContactChooseActivity.startWithInviteMember(this, chatInfo.id, orgi_membersList);
            }
        } else if (member.isOptDel()) {
            if (isManager) {//删除管理员
                ContactChooseActivity.startWithRemoveManager(this, chatInfo.id, orgi_memberIsManagersList);
            } else {//删除成员
                ContactChooseActivity.startWithRemoveMember(this, chatInfo.id, orgi_membersList, orgi_memberIsManagersList);
            }
        } else {
            UserInfo user = TelegramManager.getTelegramManager().getTgData().contactInfo(member.user_id);
            if (user == null) return;
            if (member.user_id == UserInfo.getUserInfo().id) {
//                ProfileActivity.start(this);
                startContainerActivity(PersonalDataFragment.class.getCanonicalName());
            } else {
//                if (super_groupInfo != null && super_groupInfo.status != null) {
//                    TelegramManager.GroupMemberState state = super_groupInfo.status.getMemberState();
//                    if (state == TelegramManager.GroupMemberState.GroupMemberState_Administrator || state == TelegramManager.GroupMemberState.GroupMemberState_Creator) {
//                        ContactDetailActivity.start(this, user, chatInfo2.id, true);
//                    }
////                    else {
////                        ContactDetailActivity.start(this, user, !(chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper));
////                    }
//                }
//                if ((chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper))  {
//                    ContactDetailActivity.start(this, user, !(chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper));
//                }

                boolean blockContact = !(chatInfo2.permissions != null && !chatInfo2.permissions.banWhisper);
                new XPopup.Builder(this)
                        .hasShadowBg(true)
                        .isDestroyOnDismiss(true)
                        .dismissOnTouchOutside(true)
                        .borderRadius(10)
                        .atView(binding.llChatDarao)
                        .asCustom(new ChatUserDialog(this, user,blockContact, new ChatUserDialog.OnItemClickListner() {
                            @Override
                            public void clickPostion(int postion, ChatInfo chatInfo) {

                            }
                        })).show();
            }
        }
    }

    //系统通知
    private MessageInfo lastPinnedMsg;
    private boolean isRequestsyncFullGroupInfo = false;

    @Override
    protected void onResume() {
        super.onResume();
        //显示群通知
        resetNoticeInfo();
        //同步群通知
        syncGroupNotice();
        if (!isRequestsyncFullGroupInfo) {
            syncFullGroupInfo();
        }
    }

    private List<GroupMemberInfo> groupMemberInfos = new ArrayList<>();
    private  int offset = 0;

    private void getAllSuperMembers(){
        TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterRecent", null, offset, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    if(obj.size() + offset  < response.get("total_count").getAsInt()){
                        groupMemberInfos.addAll(obj);
                        offset = offset + obj.size();
                        getAllSuperMembers();
                    }else{
                        groupMemberInfos.addAll(obj);
                        resetMembersListUI();
                        resetUI();
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    public void getSuperMembers() {

        getAllSuperMembers();
        TelegramManager.getTelegramManager().getSuperGroupMembers(this, chatInfo.id,chatInfo.superGroupId(), null, null, 0, 1000, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_membersList.clear();
                    if (obj.size() > 0) {
                        orgi_membersList.addAll(obj);
                    }
                    groupSettingViewModel.groupInfoLiveData().postValue(orgi_membersList);
                    resetMembersListUI();
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private String annContentStr = null;
    private String summerContentStr = null;
    private String groupUserNickName = null;

    private void resetGroupNickName(){
        TelegramManager.getTelegramManager().getGroupMember(this, chatInfo.id, UserInfo.getUserInfo().id, new TgResultBlock<GroupMemberInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, GroupMemberInfo obj) {
                groupUserNickName = obj==null?UserInfo.getUserInfo().displayName():obj.nickname;
                resetUI();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    //群通知
    private void resetNoticeInfo() {
        if (lastPinnedMsg != null) {
            String text = lastPinnedMsg.toString();
            if (text.startsWith(Constants.GROUP_NOTICE_PREFIX)) {
                text = text.substring(Constants.GROUP_NOTICE_PREFIX.length());
            } else if (text.startsWith(Constants.GROUP_NOTICE_PREFIX.trim())) {
                text = text.substring(Constants.GROUP_NOTICE_PREFIX.trim().length());
            }
            annContentStr = text;
//            binding.annContent.setText(text);
        } else {
//            binding.annContent.setText(getString(R.string.not_set));
        }
    }

    //同步群通知
    private void syncGroupNotice() {
        TelegramManager.getTelegramManager().getGroupNotice(this, chatInfo.id, new TgResultBlock<MessageInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                if (obj != null) {
                    lastPinnedMsg = obj;
                    resetNoticeInfo();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        isRequestsyncFullGroupInfo = false;
    }

    private void checkUserChatState() {
        TelegramManager.getTelegramManager().getSuperGroupInfo(this, chatInfo.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                if (obj != null) {
                    super_groupInfo = obj;

                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private void syncFullGroupInfo() {
        isRequestsyncFullGroupInfo = true;
        TelegramManager.getTelegramManager().getGroupNotice(this, chatInfo.id, new TgResultBlock<MessageInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, MessageInfo obj) {
                realRequestFullGroupInfo();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                realRequestFullGroupInfo();
            }
        });
    }

    private void realRequestFullGroupInfo() {
        TelegramManager.getTelegramManager().getSuperGroupFullInfo(this, chatInfo.superGroupId(), new TgResultBlock<SuperGroupFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, SuperGroupFullInfo obj) {
                if (obj != null) {
                    super_groupFullInfo = obj;
                    resetUI();
                    //获取超级群组成员列表
                    getSuperMembers();
                    //获取超级群组管理员列表
                    getSuperAdminMembers();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    public void getSuperAdminMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterAdministrators", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                if (obj != null) {
                    orgi_memberIsManagersList.clear();
                    if (obj.size() > 0) {
                        orgi_memberIsManagersList.addAll(obj);
                    }
                    resetMamagerMembersListUI();
                    resetUI();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }

    private boolean canEditGroupSetting() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Administrator:
                    //管理员
                    return true;
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                case GroupMemberState_Left:
                    //不在群组
                    break;
                case GroupMemberState_Member:
                    //普通成员
                    break;
                case GroupMemberState_Banned:
                    //被禁用
                    break;
                case GroupMemberState_Restricted:
                    //被禁言
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private boolean canEditGroupManagerSetting() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private boolean isOwnerGroup() {
        if (super_groupInfo != null && super_groupInfo.status != null) {
            switch (super_groupInfo.status.getMemberState()) {
                case GroupMemberState_Creator:
                    //创建者
                    if (super_groupInfo.status.is_member) {
                        return true;
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    public void resetMembersListUI() {

    }

    public void resetMamagerMembersListUI() {

    }


    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode  == RESULT_OK){
//            onResume();
        }
        List<String> photos = MediaUtils.getResultAlbumData(this, requestCode, resultCode, data);
        if (photos != null && photos.size() > 0) {
            changeGroupHeader(photos.get(0));
        }
    }

    private void changeGroupHeader(String localPath) {
        showProgress();
        TelegramManager.getTelegramManager().setGroupPhoto(this, chatInfo.id, localPath, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void memberListUI() {
        //管理员列表
        GridLayoutManager layoutManager = new GridLayoutManager(this, 7);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        binding.managerRecyclerView.setLayoutManager(layoutManager);
        memberIsManagerGridAdapter = new MemberGridAdapter(R.layout.adapter_grid_member_1, membersList);
        binding.managerRecyclerView.setAdapter(memberIsManagerGridAdapter);
        memberIsManagerGridAdapter.setOnItemClickListener((adapter, view1, position) -> {
            GroupMemberInfo member = membersList.get(position);
            clickMember(member, true);
        });
        getTotalSuperMembers();
    }

    public void getTotalSuperMembers() {
        TelegramManager.getTelegramManager().getSuperGroupMembers(this,chatInfo.id, chatInfo.superGroupId(), "supergroupMembersFilterRecent", null, 0, 200, new TgResultBlock<List<GroupMemberInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<GroupMemberInfo> obj) {
                membersList.clear();
                if (obj != null) {
//                    if (obj.size() > 0) {
//                        membersList.addAll(obj);
//                    }
                    int num = obj.size();
                    if(obj.size()> 14){
                        membersList.addAll(obj.subList(0,14));
                    }else {
                        membersList.addAll(obj);
                    }
                    binding.managerListNum.setText(num+"");
                    memberIsManagerGridAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
    }
}
